package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.*;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        StoredProcedureQuery getAllPersonsQuery = em.createNamedStoredProcedureQuery("getAllPersons");
        List<Person> persons = getAllPersonsQuery.getResultList();
        for (Person person : persons) {
            StoredProcedureQuery query = em.createNamedStoredProcedureQuery("myPersons");
            query.setParameter(2, person.getId());
            Person singlePerson = (Person) query.getResultList().get(0);
            System.err.println(JSONObject.toJSONString(singlePerson, true));
        }

        em.close();
        emf.close();
    }

    private static void getSumFromProcedure(EntityManagerFactory emf) {
        EntityManager em = emf.createEntityManager();
        StoredProcedureQuery query = em.createStoredProcedureQuery("calculate");
        query.registerStoredProcedureParameter("x",Double.class, ParameterMode.IN);
        query.registerStoredProcedureParameter("y",Double.class,ParameterMode.IN);
        query.registerStoredProcedureParameter("sum",Double.class,ParameterMode.OUT);
        query.setParameter("x",1.23d);
        query.setParameter("y",4.56d);
        query.execute();
        Double sum = (Double) query.getOutputParameterValue("sum");
        System.err.println("sum=" + sum);
        em.close();
    }
}
